import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAppDispatch, useAppSelector } from '../../store/hooks'
import { loginStart, loginSuccess, loginFailure } from '../../store/slices/authSlice'
import './login.css'

function Index() {
  const [formData, setFormData] = useState({
    username: '',
    password: ''
  })
  const [errors, setErrors] = useState({
    username: '',
    password: ''
  })
  
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  const { isLoading, error } = useAppSelector((state) => state.auth)

  // 页面加载时检查本地存储的凭据
  React.useEffect(() => {
    const savedCredentials = localStorage.getItem('userCredentials')
    if (savedCredentials) {
      try {
        const credentials = JSON.parse(savedCredentials)
        setFormData({
          username: credentials.username || '',
          password: credentials.password || ''
        })
      } catch (error) {
        console.error('解析保存的凭据失败:', error)
      }
    }
  }, [])

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
    // 清除对应字段的错误信息
    if (errors[name as keyof typeof errors]) {
      setErrors(prev => ({
        ...prev,
        [name]: ''
      }))
    }
  }

/**
 * 验证表单数据的函数
 * 检查用户名和密码字段是否有效
 * @returns {boolean} - 如果所有字段都有效则返回true，否则返回false
 */
  const validateForm = () => {
  // 初始化错误对象，包含用户名和密码字段
    const newErrors = {
      username: '',
      password: ''
    }
    
  // 验证用户名：如果为空或只包含空白字符，则设置错误信息
    if (!formData.username.trim()) {
      newErrors.username = '请输入用户名'
    }
    
  // 验证密码：如果为空或只包含空白字符，设置错误信息
  // 如果密码长度小于6位，设置相应的错误信息
    if (!formData.password.trim()) {
      // 设置密码错误信息
      newErrors.password = '请输入密码'    // 当密码为空时，设置错误提示
    } else if (formData.password.length < 6) {  // 检查密码长度是否符合要求
      newErrors.password = '密码长度至少6位'  // 设置密码长度不足的错误信息
    }
    
  // 更新错误状态，将新的错误信息设置到组件状态中
    setErrors(newErrors)
  // 检查是否有任何错误，如果没有则返回true
    return !newErrors.username && !newErrors.password
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!validateForm()) {
      return
    }
    
    try {
      dispatch(loginStart())
      
      // 模拟登录API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 这里可以添加实际的登录API调用
      // const response = await loginAPI(formData)
      
      // 模拟登录成功
      if (formData.username === 'admin' && formData.password === '123456') {
        // 保存用户凭据到本地存储
        localStorage.setItem('userCredentials', JSON.stringify({
          username: formData.username,
          password: formData.password,
          saveTime: new Date().toISOString()
        }))
        
        // 模拟API返回的登录响应
        const mockLoginResponse = {
          token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWQiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE2MzQ1Njc4OTAsImV4cCI6MTYzNDY1NDI5MH0.mock_signature',
          user: {
            username: formData.username,
            id: '1234567890',
            role: 'user'
          }
        }
        
        // 使用 Redux 保存登录状态
        dispatch(loginSuccess(mockLoginResponse))
        
        // 跳转到首页
        navigate('/home')
      } else {
        dispatch(loginFailure('用户名或密码错误！\n提示：用户名：admin，密码：123456'))
      }
    } catch (error) {
      dispatch(loginFailure('登录失败，请重试'))
    }
  }

  return (
    <div className="login-container">
      <div className="login-box">
        <div className="login-header">
          <div className="logo-section">
            <div className="medical-logo">
              <svg viewBox="0 0 24 24" fill="currentColor" className="logo-icon">
                {/* 医疗十字图标 */}
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V7h2v2zm4 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V7h2v2z"/>
                {/* 心跳线 */}
                <path d="M12 6c-1.1 0-2 .9-2 2v2c0 .55-.45 1-1 1s-1-.45-1-1V8c0-1.1-.9-2-2-2s-2 .9-2 2v2c0 1.1.9 2 2 2s2-.9 2-2v-2c0-.55.45-1 1-1s1 .45 1 1v2c0 1.1.9 2 2 2s2-.9 2-2V8c0-1.1-.9-2-2-2z"/>
              </svg>
            </div>
            <h1 className="app-title">医疗管理</h1>
            <p className="app-subtitle">Medical Management System</p>
          </div>
          <p>欢迎回来，请登录您的账户</p>
        </div>
        
        <form onSubmit={handleSubmit} className="login-form">
          {error && <div className="error-message">{error}</div>}
          
          <div className="form-group">
            <label htmlFor="username">用户名</label>
            <input
              type="text"
              id="username"
              name="username"
              value={formData.username}
              onChange={handleInputChange}
              placeholder="请输入用户名"
              className={errors.username ? 'error' : ''}
            />
            {errors.username && <span className="error-message">{errors.username}</span>}
          </div>
          
          <div className="form-group">
            <label htmlFor="password">密码</label>
            <input
              type="password"
              id="password"
              name="password"
              value={formData.password}
              onChange={handleInputChange}
              placeholder="请输入密码"
              className={errors.password ? 'error' : ''}
            />
            {errors.password && <span className="error-message">{errors.password}</span>}
          </div>
          
          <div className="form-options">
            <label className="checkbox-container">
              <input type="checkbox" />
              <span className="checkmark"></span>
              记住我
            </label>
            <a href="#" className="forgot-password">忘记密码？</a>
          </div>
          
          <button 
            type="submit" 
            className="login-btn"
            disabled={isLoading}
          >
            {isLoading ? '登录中...' : '登录'}
          </button>
        </form>
        
        <div className="login-footer">
          <p>还没有账户？ <a href="#">立即注册</a></p>
        </div>
      </div>
    </div>
  )
}

export default Index